package dawn.service.socket;

import java.util.concurrent.ConcurrentLinkedQueue;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import dawn.net.Message;
import dawn.net.protocol.IDecoder;
import dawn.service.OnlineService;

public class SocketHandler extends IoHandlerAdapter {

    @Override
	public void exceptionCaught(IoSession session, Throwable cause)
            throws Exception {
        System.out.println("exceptionCaught：" + session.getId());
        session.close(true);
    }

    @Override
    public void messageReceived(IoSession session, Object message)
            throws Exception {
        String str = message.toString();
        IDecoder decode = (IDecoder) session
                .getAttribute(SessionAttribute.DECODER);

        if (decode != null) {
            decode.decode(session, str);
        } else {
            session.close(false);
        }
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status)
            throws Exception {

        System.out.println("session idle" + session.getId());
    }

    /**
     * 当创建一个session时的操作
     * 
     */
    @Override
	public void sessionCreated(IoSession session) throws Exception {
        System.out.println("客户端连接：" + session.getId());
        //        LOGGER.debug(session.getId() + "has been connect ");

        // 为session添加一个没有经过处理的属性，里面放的是所没有经过逻辑线程处理的消息
        session.setAttribute(SessionAttribute.MESSAGES,
                new ConcurrentLinkedQueue<Message>());

        OnlineService.getNotAuthMap().put(session.getId(), session); // 将session放入到未登录的集合中
    }

    @Override
	public void sessionOpened(IoSession session) throws Exception {
        System.out.println("socket打开：" + session.getId());
    }

    @Override
	public void sessionClosed(IoSession session) throws Exception {
        System.out.println("socket关闭" + session.getId());
    }

    @Override
	public void messageSent(IoSession session, Object message) throws Exception {}
}